package controller

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/go-pay/gopay/alipay"
	"ksd-social-api/commons/base/controller"
	utils2 "ksd-social-api/utils"
	"net/url"
	"strconv"
	"strings"
)

type AlipayNativeController struct {
	controller.BaseController
}

/*
*
* 判断支付宝支付回调
* @author feige
* @date 2023-12-04
* @version 1.0
* @desc
 */
func (web *AlipayNativeController) QueryOrderByOutTradeNotify() {
	fmt.Println("支付宝支付回调进来了")
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("支付宝：数据已保存！")
			web.Ok("ok")
		}
	}()
	publicKey := beego.AppConfig.DefaultString("alipay.pay.publicKey", "")
	// 获取你支付的回调参数, 也就是说支付宝服务器会把你所有的订单信息放入到请求体
	values, err := url.ParseQuery(string(web.Ctx.Input.RequestBody))
	if err != nil {
		web.FailCodeMsg(910, "支付失败")
		return
	}
	datas, err := alipay.ParseNotifyByURLValues(values) //证书异步验签
	if err != nil {
		web.FailCodeMsg(910, "支付失败")
		return
	}

	//验签
	ok, err := alipay.VerifySign(publicKey, datas)
	if ok == false || err != nil {
		web.FailCodeMsg(910, "校验失败")
		return
	}
	fmt.Println("支付的数据：", datas)

	tradeStatus := datas.Get("trade_status")
	fmt.Println("支付状态：", tradeStatus)
	tmp := make(map[string]interface{})
	if tradeStatus == "TRADE_SUCCESS" {
		modes := strings.Split(datas.Get("out_trade_no"), "_")
		if len(modes) >= 4 {
			TransactionId := datas.Get("trade_no")
			Price := datas.GetString("total_amount")
			OutTradeNo := modes[0]
			Mode := modes[1]
			UserId, _ := strconv.ParseUint(modes[2], 10, 64)
			Opid, _ := strconv.ParseUint(modes[3], 10, 64)
			fmt.Println("%s,%s,%d,%d", OutTradeNo, Mode, UserId, Opid)
			if Mode == "note" {
				fmt.Println("支付宝支付回调进来了，note----start")
				isBuyFlag := userNoteService.CountUserBuyNote(UserId, Opid, web.GetSystemId())
				fmt.Println("支付宝支付回调进来了，note----isBuyFlag", isBuyFlag)
				if !isBuyFlag {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				fmt.Println("支付宝支付回调进来了，note----isBuyFlag---2", isBuyFlag)
				userNoteService.SaveUserNote(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					UserId, Opid, web.GetSystemId(), web.GetSystemName())
				fmt.Println("支付宝支付回调进来了，note----end")
			} else if Mode == "channel" {
				fmt.Println("微信支付回调进来了，note----start")
				isBuyFlag := userBuyChannelService.CountUserBuyChannel(UserId, Opid, web.GetSystemId())
				fmt.Println("微信支付回调进来了，note----isBuyFlag", isBuyFlag)
				if !isBuyFlag {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				fmt.Println("微信支付回调进来了，note----isBuyFlag---2", isBuyFlag)
				userBuyChannelService.SaveUserBuyChannel(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 1, "支付宝", Price,
					UserId, Opid, web.GetSystemId(), web.GetSystemName())
				fmt.Println("微信支付回调进来了，note----end")
			} else if Mode == "special" {
				fmt.Println("支付宝支付回调进来了，special----start")
				isBuyFlag := userSpecialService.CountUserBuySpecial(UserId, Opid, web.GetSystemId())
				if !isBuyFlag {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				// 订单保存落库
				userSpecialService.SaveUserSpecial(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					UserId, Opid, web.GetSystemId(), web.GetSystemName())

				fmt.Println("支付宝支付回调进来了，special----end")
			} else if Mode == "specialbind" {
				fmt.Println("支付宝支付回调进来了，specialbind----start")
				SpecialId, _ := strconv.ParseUint(modes[4], 10, 64)
				isBuyFlag := userSpecialBindService.CountUserBuySpecialBind(UserId, SpecialId, Opid, web.GetSystemId())
				if !isBuyFlag {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				// 订单保存落库
				userSpecialBindService.SaveUserSpecialBind(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					UserId, Opid, SpecialId, web.GetSystemId(), web.GetSystemName())
				fmt.Println("支付宝支付回调进来了，specialbind----end")
			} else if Mode == "coin" {
				fmt.Println("支付宝支付回调进来了，coin----start")
				isBuyFlag := userWalletService.CountUserWalletRecordsByOutTradeNo(OutTradeNo, web.GetSystemId())
				if isBuyFlag > 0 {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				// 订单保存落库
				userWalletService.SaveUserWalletRecords(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					web.GetUserId(), web.GetSystemId(), web.GetSystemName())
				fmt.Println("支付宝支付回调进来了，coin----end")
			} else if Mode == "vip" {
				fmt.Println("支付宝支付回调进来了，vip----start")
				isBuyFlag := userBuyVipService.CountUserBuyVipByOutTradeNo(OutTradeNo, web.GetSystemId())
				fmt.Println("支付宝支付回调进来了，vip----isBuyFlag", isBuyFlag)
				if isBuyFlag > 0 {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				// 订单保存落库
				userBuyVipService.SaveUserVipOrder(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					web.GetUserId(), Opid, web.GetSystemId(), web.GetSystemName())
				fmt.Println("支付宝支付回调进来了，vip----end")
			} else if Mode == "resume" {
				fmt.Println("支付宝支付回调进来了，resume----start")
				resumeId, _ := strconv.ParseUint(modes[4], 10, 64)
				// 订单保存落库
				resumeService.UpdateResumePay(resumeId, 2, "支付宝", TransactionId, web.GetUserId(), web.GetSystemId())
				fmt.Println("支付宝支付回调进来了，specialbind----end")
			} else if Mode == "resumetemplate" {
				fmt.Println("支付宝支付回调进来了，special----start")
				isBuyFlag := userResumeTemplateService.CountUserBuyResumeTemplate(UserId, Opid, web.GetSystemId())
				if !isBuyFlag {
					web.FailCodeMsg(902, "订单已经创建")
					return
				}
				// 订单保存落库
				userResumeTemplateService.SaveUserResumeTemplate(
					OutTradeNo, TransactionId, utils2.StructToJson(datas), 2, "支付宝", Price,
					UserId, Opid, web.GetSystemId(), web.GetSystemName())

				fmt.Println("支付宝支付回调进来了，special----end")
			}
		}
		tmp["code"] = "SUCCESS"
		tmp["message"] = "成功"
	} else {
		tmp["code"] = "500"
		tmp["message"] = "失败"
	}

	web.Ok(tmp)
}

/*
*
* 判断支付宝支付回调
* @author feige
* @date 2023-12-04
* @version 1.0
* @desc
 */
func (web *AlipayNativeController) QueryOrderByOutTradeReturn() {
	fmt.Println("alipay---------------->return支付成功")
	web.Ok("success")
}
